package com.cxh.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.cxh.constant.SsmConstant;
import com.cxh.entity.Item;
import com.cxh.entity.User;
import com.cxh.enums.ExceptionInfoEnum;
import com.cxh.exception.SsmException;
import com.cxh.mapper.UserMapper;
import com.cxh.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.UUID;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    public UserMapper userMapper;

    @Override
    public void checkUsername(String username) {
        User param = new User();
        param.setUsername(username);
        int result = userMapper.selectCount(param);
        if (result != 0) {
            log.info("【异步校验用户名】 用户名不可用!!! username = {}", username);
            throw new SsmException(11, "用户名不可用！");
        }

    }

    @Override
    public void register(User user) {
        //生成盐
        String salt = UUID.randomUUID().toString();
        //加密传进来的密码
        String newPassword = new Md5Hash(user.getPassword(), salt, SsmConstant.HASH_ITERATIONS).toString();
        user.setSalt(salt);
        user.setPassword(newPassword);
        int result = userMapper.insertSelective(user);
        //判断是否注册成功
        if (result != 1) {
            log.error("【注册账号】 注册账号失败 user = {}", user);
            throw new SsmException(ExceptionInfoEnum.USER_REGISTER_ERROR);
        }
    }

    @Override
    public User login(String username, String password) {
        User param = new User();
        param.setUsername(username);
        User user = userMapper.selectOne(param);
        if (user == null) {
            log.info("【登录功能】 用户名不存在! username = {}", username);
            throw new SsmException(ExceptionInfoEnum.USER_USERNAME_ERROR);
        }
        String newPassword = new Md5Hash(password, user.getSalt(), SsmConstant.HASH_ITERATIONS).toString();
        if (!user.getPassword().equals(newPassword)) {
            log.info("【登录功能】 密码错误! user = {},username = {},password = {}", user, username, password);
            throw new SsmException(ExceptionInfoEnum.USER_PASSWORD_ERROR);
        }

        return user;
    }


}
